#include "LED.h"

#include <WProgram.h>

#include "Bounce/ObservableBounce.h"

#include "Thermostat.h"

LED::LED(uint8_t redPin, uint8_t greenPin, uint8_t bluePin,
         ObservableBounce *doorSwitch, Thermostat *thermostat) {
  this->doorSwitch = doorSwitch;
  this->thermostat = thermostat;
  
  this->redPin = redPin;
  this->greenPin = greenPin;
  this->bluePin = bluePin;
  

}

void LED::init() {
  //Flash LED colors in a pattern on startup    
  pinMode(redPin, OUTPUT);
  analogWrite(redPin, 255);
  delay(100);
  pinMode(greenPin, OUTPUT);
  analogWrite(greenPin, 255);
  delay(100);
  pinMode(bluePin, OUTPUT);
  analogWrite(bluePin, 255);
  delay(100);
}

void LED::update(Observable *o) {
  if (doorSwitch->read() == 0) { //Door closed, just keep off
    setColor(0, 0, 0);
    return;
  }
  updateColor();
}

void LED::setColor(int red, int green, int blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void LED::updateColor() {
  int red = 0;
  int green = 0;
  int blue = 0;
  float tempError = thermostat->getTempError();
  float tempRange = thermostat->getTempRange()*2;
  
  if (tempError >= tempRange) {
    red = 255;
    blue = green = 0;
  } 
  else if (tempError >= tempRange/2) {
    blue = 0;
    red = 255;
    green = int( (-255/(tempRange/2)) * (tempError-tempRange) );
  }
  else if (tempError >= 0) {
    red = green = 255;
    blue = int( (-255/(tempRange/2)) * (tempError-(tempRange/2)) );
  }
  else if (tempError <= -tempRange) {
    blue = 255;
    red = green = 0;
  }
  else if (tempError <= -(tempRange/2)) {
    blue = 255;
    red = 0;
    green = int( (255/(tempRange/2)) * (tempError + tempRange) );
  }
  else if (tempError < 0) {
    blue = green = 255;
    red = int ( (255/(tempRange/2)) * (tempError + (tempRange/2)) );
  }
  setColor(red, green, blue);
}
